package com.xss.bitmaptest.util;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * Created by Administrator on 2018/9/12.
 */

public class BitmapUtil {
    private static final String TAG = "BitmapUtil";

    /**
     * 获取采样率，高效加载图片
     *
     * @param res       资源
     * @param resId     图片资源id
     * @param reqWidth  目标图片的宽
     * @param reqHeight 目标图片的高
     * @return 处理好的所需尺寸的Bitmap
     */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {
        //通过inJustDecodeBounds=true，使Bitmap解析图片宽高信息，并不会真正的的加载图片
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        //计算采样率
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        //重新加载图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    /**
     * 根据采样率规则并结合目标View所需大小计算采样率
     *
     * @param options   BitmapFactory.Options
     * @param reqWidth  目标view所需图片宽
     * @param reqHeight 目标view所图片高
     * @return 计算后的采样率
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        //获取图片原始宽高
        final int height = options.outHeight;
        final int width = options.outWidth;
        Log.d(TAG, "calculateInSampleSize: out：" + height + "-" + width);
        int inSampleSize = 1;

        //根据采样率规则并结合目标View所需大小计算采样率
        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        Log.d(TAG, "calculateInSampleSize: 采样率：" + inSampleSize);
        return inSampleSize;
    }
}
